/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author charliemalchow
 */

import java.sql.*;
import java.util.*;
import javax.swing.JOptionPane;

class Score {
    public double score = 0.0;
    public Survey s1;
    
    public Score (double score, Survey s1) {
        this.score = score;
        this.s1 = s1;
    }
}


public class Matchmaker {
    public ArrayList<Survey> surveys = new ArrayList<Survey>();
    
    private Connection connect;
    
    public Matchmaker() {
        //Load all surveys...
        connectToDB();
        loadFromDB();
    }
    
    private void loadFromDB(){
        try {
            String loadQuery = "SELECT studentID FROM DORMS.survey";
            PreparedStatement loadStmt = connect.prepareStatement(loadQuery);
            //loadStmt.setInt(1, requestID);
            ResultSet surveysReturned = loadStmt.executeQuery();
            while(surveysReturned.next()){
                Survey newSurvey = new Survey(surveysReturned.getInt("studentID"), connect);
                this.surveys.add(newSurvey);
            }
            
        } catch (Exception ex){
            JOptionPane.showMessageDialog(null,
                    "Unable to load request from database.");
        }
        
    }
    
    public ArrayList<Survey> getSuggestions(Survey survey) {
        
        MatchProcessor m = new MatchProcessor();
        
        ArrayList<Survey> matchs = new ArrayList<Survey>();
        ArrayList<Score> scores = new ArrayList<Score>();
        
        double max_of_mins = 0.0;
        
        for (int i=0; i < surveys.size(); i++) {
            if (!surveys.get(i).equals(survey)) {
                double score = m.computeScore(survey, surveys.get(i));
                Score s = new Score(score, surveys.get(i));
                scores.add(s);
            }
        }
        
        double min_score = 0.0;
        int min = 0;
        for (int i=0; i < 5; i++) {
            for (int j=0; j < scores.size(); j++) {
                Score s = scores.get(j);
                if (s.score <= min_score || min_score == 0.0) {
                    min  = j;
                    min_score = s.score;
                }
            }
            matchs.add(scores.get(min).s1);
            scores.remove(min);
        }
        
        return matchs;
    }
    
    private void connectToDB()
    {
        try 
        {
            // Load the JDBC driver
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("Driver loaded");

            // Establish a connection
            connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DORMS?user=root&password=dorms");
            System.out.println("Database connected");

            // Create a Statement
            //stmt = (Statement) conn.createStatement();

        } 
        catch (Exception ex) 
        {
            System.out.println(ex);
        }
    }

}
